var AV = require('leanengine');
var avAwardBatch 	= AV.Object.extend("AwardBatch");
var avAwardPool 	= AV.Object.extend("AwardPool");
var avLottery 		= AV.Object.extend("Lottery");
var avSysConfig 	= AV.Object.extend("SysConfig");


AV.Cloud.define('updateAwardPool', function(request, response) {
  var item,newItem,Lottery,total=0;
  var name	        = request.params.name;
  var queryLottery 	= new AV.Query(avLottery);
  if(!name)name="daily";
  queryLottery.equalTo("name",name);
	queryLottery.first().then(function(result){
    if(typeof(result)=="undefined"){
      return AV.Promise.error("抽奖不存在！");
    }else{
      Lottery=result;
      return AV.Query.doCloudQuery("select objectId from AwardPool where lottery=pointer('Lottery','"+Lottery.id+"') and userLottery is not exists");
    }
  }).then(function(result){
    return AV.Object.destroyAll(result.results);
  }).then(function(results){
    var promises=[];
    item = Lottery.get("item");
    for(var i=0;i<item.length;i++){
      //console.dir(item);
      //console.dir(item[i]);
      if(item[i].isItem=='true'){
        //console.dir(item[i].num);
        var AwardPools        = [];
        var AwardBatch        = new avAwardBatch();
        AwardBatch.id         = item[i].id;
        for(var j=0;j<item[i].num;j++){
          AwardPools[j]   = new avAwardPool();
          AwardPools[j].set("awardBatch",AwardBatch);
          AwardPools[j].set("lottery",Lottery);
          AwardPools[j].set("name",item[i].name);
          promises.push(AwardPools[j].save());
        }
        total+=parseInt(item[i].num);
      }
    }
    Lottery.set("total",total);
    Lottery.set("starttime",moment().toDate());
    Lottery.set("endtime",moment().endOf("day").toDate());
    promises.push(Lottery.save());
    return AV.Promise.all(promises);
  }).then(function(results){
    //console.log(results.length);
    console.log("updateAwardPool("+name+"):success!");
  	response.success();
  },function(error){
  	if(typeof(error)=="object"){
  		console.error("updateAwardPool("+name+"):" + error.message);
  		response.error(404);
  	}else{
  		response.error(error);
  	}
  });

})

module.exports = AV.Cloud;
